package com.useeinfo.oa.open.admin.maintaining;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.func.excel.ExcelExport;
import com.useeinfo.framework.sugar.tools.*;
import com.useeinfo.oa.common.config.ExcelExportMap;
import com.useeinfo.oa.common.utils.CommonUtils;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.FacilityBiz;
import com.useeinfo.oa.modules.base.biz.PositionBiz;
import com.useeinfo.oa.modules.base.entity.*;
import com.useeinfo.oa.modules.inspection.entity.FacilityInspectionSnap;
import com.useeinfo.oa.modules.maintaining.biz.*;
import com.useeinfo.oa.modules.maintaining.entity.*;
import com.useeinfo.oa.modules.maintaining.enums.ApplyTypeEnum;
import com.useeinfo.oa.modules.maintaining.enums.OrderOperationEnum;
import com.useeinfo.oa.modules.maintaining.enums.OrderStatusEnum;
import com.useeinfo.oa.modules.repair.entity.RepairOrder;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Auther: xudong.sun
 * @Date: 2019/1/4 09:44
 * @Description:
 */
@Controller
@RequestMapping("/web/admin/maintainOrder")
public class MaintainOrderAction {

    @Autowired
    private MaintainOrderBiz maintainOrderBiz;
    @Autowired
    private FacilityMaintainSnapBiz facilityMaintainSnapBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private ApplyOrderBiz applyOrderBiz;
    @Autowired
    private AuditOrderBiz auditOrderBiz;
    @Autowired
    private MaintainOrderWorkContentBiz maintainOrderWorkContentBiz;
    @Autowired
    private MaintainOrderLogBiz maintainOrderLogBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private WorkContentRemarkBiz workContentRemarkBiz;


    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        //查询工单状态枚举类list
        JSONArray orderStatusArray = new JSONArray();
        for (OrderStatusEnum orderStatusEnum : OrderStatusEnum.values()) {
            JSONObject json = new JSONObject();
            json.put("name", orderStatusEnum.getName());
            json.put("code", orderStatusEnum.getCode());
            orderStatusArray.add(json);
        }
        modelAndView.addObject("orderStatusArray", orderStatusArray);
        modelAndView.setViewName("pages/admin/maintainOrder/list");
        return modelAndView;
    }


    /**
     * 获取维保单列表
     * @param pageNowParam
     * @param pageSizeParam
     * @param searchName 工单名
     * @param searchCode 单号
     * @param searchOrderStatus 工单状态 （审批，完成等）
     * @param startTimeParam 开始时间
     * @param endTimeParam 结束时间
     * @param searchType 工单类型 false 周期性  true 一次性
     * @param searchDegree 紧急程度
     * @param request
     * @return JSONObject
     */
    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchName", required = false) String searchName,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "searchOrderStatus", required = false) String searchOrderStatus,
                               @RequestParam(value = "startTime", required = false) String startTimeParam,
                               @RequestParam(value = "endTime", required = false) String endTimeParam,
                               @RequestParam(value = "searchType", required = false) String searchType,
                               @RequestParam(value = "searchDegree", required = false) String searchDegree,
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.getSqlMap().put("searchName", searchName);
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("searchOrderStatus", searchOrderStatus);
        queryParam.getSqlMap().put("searchDate1", startTimeParam);
        queryParam.getSqlMap().put("searchDate2", endTimeParam);
        queryParam.getSqlMap().put("orderType", searchType);
        queryParam.getSqlMap().put("degree", searchDegree);
        return maintainOrderBiz.findJSONList(queryParam);
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id, HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.ToLong(id));
        if (maintainOrder == null) {
            maintainOrder = new MaintainOrder();
            maintainOrder.setSerial(CommonUtils.getRandomNumber(10));
            maintainOrder.setOrderCode("保存后生成");
        }
        String filePath = "";
        String fileName = "";
        if (maintainOrder.getResource() != null) {
            Resource resource = maintainOrder.getResource();
            filePath = Configuration.getConfigurationByName("hostUrl") + "/" + resource.getPath();
            fileName = resource.getResourceName();
        }
        modelAndView.addObject("fileName", fileName);
        modelAndView.addObject("filePath", filePath);
        modelAndView.addObject("maintainOrder", maintainOrder);
        modelAndView.setViewName("pages/admin/maintainOrder/edit");
        return modelAndView;
    }

    /**
     * 获取详情页面
     */
    @RequestMapping("/viewPage")
    public ModelAndView viewPage(@RequestParam(value = "id", required = false) String id) {
        ModelAndView modelAndView = new ModelAndView();
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("maintainOrder", maintainOrder);
        modelAndView.addObject("status", maintainOrder.getOrderStatusEnum().getName());
        List<SelectVO> list = new ArrayList<>();
        if (StringUtils.isNotBlank(maintainOrder.getCompleteFlow())) {
            JSONArray jsonArray = JSONArray.parseArray(maintainOrder.getCompleteFlow());
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
                    SelectVO selectVO = new SelectVO();
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    String organizationName=organizationBiz.findModel(StringConverters.null2Long(organizationId)).getOrganizationName();
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    selectVO.setText(relationId.toString());
                    if ("POSITION".equals(nodeTypeEnum)) {
                        selectVO.setValue(organizationName+" 岗位 " + positionBiz.findModel(StringConverters.null2Long(relationId)).getName());
                    } else if ("USER".equals(nodeTypeEnum)) {
                        selectVO.setValue(organizationName+" 用户 " + systemUserBiz.findModel(StringConverters.null2Long(relationId)).getUserName());
                    }
                    list.add(selectVO);
                }
            }
        }
        modelAndView.addObject("completeFlow", list);
        List<SelectVO> delayList = new ArrayList<>();
        if (StringUtils.isNotBlank(maintainOrder.getDelayFlow())) {
            JSONArray jsonArray = JSONArray.parseArray(maintainOrder.getDelayFlow());
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
                    SelectVO selectVO = new SelectVO();
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    String organizationName=organizationBiz.findModel(StringConverters.null2Long(organizationId)).getOrganizationName();
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    selectVO.setText(relationId.toString());
                    if ("POSITION".equals(nodeTypeEnum)) {
                        selectVO.setValue(organizationName+" 岗位 " + positionBiz.findModel(StringConverters.null2Long(relationId)).getName());
                    } else if ("USER".equals(nodeTypeEnum)) {
                        selectVO.setValue(organizationName+" 用户 " + systemUserBiz.findModel(StringConverters.null2Long(relationId)).getUserName());
                    }
                    delayList.add(selectVO);
                }
            }
        }
        modelAndView.addObject("delayFlow", delayList);
        List<SelectVO> cancelList = new ArrayList<>();
        if (StringUtils.isNotBlank(maintainOrder.getCancelFlow())) {
            JSONArray jsonArray = JSONArray.parseArray(maintainOrder.getCancelFlow());
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject j = jsonArray.getJSONObject(i);
                    SelectVO selectVO = new SelectVO();
                    Long organizationId = AliJsonObjectCover.ObjectLong(j, "organizationId");
                    String organizationName=organizationBiz.findModel(StringConverters.null2Long(organizationId)).getOrganizationName();
                    Long relationId = AliJsonObjectCover.ObjectLong(j, "relationId");
                    String nodeTypeEnum = AliJsonObjectCover.ObjectString(j, "nodeTypeEnum");
                    selectVO.setText(relationId.toString());
                    if ("POSITION".equals(nodeTypeEnum)) {
                        selectVO.setValue(organizationName+" 岗位 " + positionBiz.findModel(StringConverters.null2Long(relationId)).getName());
                    } else if ("USER".equals(nodeTypeEnum)) {
                        selectVO.setValue(organizationName+" 用户 " + systemUserBiz.findModel(StringConverters.null2Long(relationId)).getUserName());
                    }
                    cancelList.add(selectVO);
                }
            }
        }
        modelAndView.addObject("cancelFlow", cancelList);

        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("maintainOrderId", id);
        modelAndView.setViewName("pages/admin/maintainOrder/detail");
        return modelAndView;
    }

    /**
     * 详情表单数据
     *
     * @param id
     * @param type
     * @return
     */
    @RequestMapping("/applyOrderList")
    @ResponseBody
    public JSONObject applyOrderList(@RequestParam(value = "id", required = false) String id,
                                     @RequestParam(value = "type", required = false) String type) {

        QueryParam queryParam = new QueryParam("-1", "-1");
        queryParam.getSqlMap().put("maintainOrderId", id);
        if ("1".equals(type)) {//申请信息
            return applyOrderBiz.findJQJSONList(queryParam);
        } else if ("2".equals(type)) {        //审核信息
            return auditOrderBiz.findJQJSONList(queryParam);
        } else if ("3".equals(type)) {        //维保内容详细
            return maintainOrderWorkContentBiz.findJQJSONList(queryParam);
        } else {        //设备工艺信息
            return facilityMaintainSnapBiz.findJQJSONList(queryParam);
        }
    }


    /**
     * 删除工单
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id, HttpServletRequest request) {
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(id));
        if (maintainOrder != null) {
            maintainOrderBiz.deleteLogic(maintainOrder);
            //添加日志
            maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.DELETE, request);
        }
        return ResultUtil.success();
    }

    /**
     * 撤回
     *
     * @param id
     * @return
     */
    @RequestMapping("/callback")
    @ResponseBody
    public ResultDto callback(String id, HttpServletRequest request) {
        //判断是否能撤回
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.ToLong(id));
        if (maintainOrder.getOrderStatusEnum() == null || !maintainOrder.getOrderStatusEnum().equals(OrderStatusEnum.WAIT_TAKING)) {
            return ResultUtil.error("该工单无法撤回");
        }
        maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_PULISHING);
        maintainOrderBiz.addOrUpdate(maintainOrder);
        //添加日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.WITHDRAW_ORDER, request);
        return ResultUtil.success();
    }

    /**
     * 发布
     *
     * @param id
     * @return
     */
    @RequestMapping("/pushUp")
    @ResponseBody
    public ResultDto pushUp(String id, HttpServletRequest request) {
        //判断是否能撤回
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.ToLong(id));
        if (maintainOrder.getOrderStatusEnum() == null) {
            return ResultUtil.error("该工单无法发布");
        }
        maintainOrder.setOrderStatusEnum(OrderStatusEnum.WAIT_TAKING);
        maintainOrderBiz.addOrUpdate(maintainOrder);
        //添加日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.RELEASE_ORDER, request);
        return ResultUtil.success();
    }

    /**
     * 废除
     *
     * @param id
     * @return
     */
    @RequestMapping("/submitDiscard")
    @ResponseBody
    public ResultDto submitDiscard(String id, HttpServletRequest request) {
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.ToLong(id));
        maintainOrder.setDiscard(true);
        maintainOrderBiz.addOrUpdate(maintainOrder);
        //添加日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.DISCARD_ORDER, request);
        return ResultUtil.success();
    }

    /**
     * 取消废除
     *
     * @param id
     * @return
     */
    @RequestMapping("/callbackDiscard")
    @ResponseBody
    public ResultDto callbackDiscard(String id, HttpServletRequest request) {
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.ToLong(id));
        maintainOrder.setDiscard(false);
        maintainOrderBiz.addOrUpdate(maintainOrder);
        //添加日志
        maintainOrderLogBiz.saveMaintainOrderLog(maintainOrder, OrderOperationEnum.CALLBACK_DISCARD_ORDER, request);
        return ResultUtil.success();
    }

    /**
     * 保存操作
     *
     * @param maintainOrder
     * @return
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(MaintainOrder maintainOrder,
                                 String facilityMaintainSnapIds, HttpServletRequest request,
                                 @RequestParam(value = "pic1", required = false) MultipartFile pic1,
                                 @RequestParam(value = "sImg1", required = false) String sImg1,
                                 @RequestParam(value = "end", required = false) String end,
                                 @RequestParam(value = "selectCompleteAuditFlowId[]", required = false) List<String> selectCompleteAuditFlowIds,
                                 @RequestParam(value = "selectDelayAuditFlowId[]", required = false) List<String> selectDelayAuditFlowIds,
                                 @RequestParam(value = "selectCancelAuditFlowId[]", required = false) List<String> selectCancelAuditFlowIds,
                                 @RequestParam(value = "selectOrganizationId[]", required = false) List<String> selectOrganizationIds
    ) {
        return maintainOrderBiz.save(maintainOrder, pic1, sImg1, end, selectCompleteAuditFlowIds, selectDelayAuditFlowIds, selectCancelAuditFlowIds, selectOrganizationIds, request);
    }


    @RequestMapping("/facilityMaintainSnapJson")
    @ResponseBody
    public JSONObject facilityMaintainSnapJson(String maintainOrderId, String serial
    ) {
        QueryParam queryParam = new QueryParam("-1", "-1");
        if (StringUtils.isNotEmpty(maintainOrderId)) {
            queryParam.getSqlMap().put("maintainOrderId", maintainOrderId);
        }
        if (StringUtils.isNotEmpty(serial)) {
            queryParam.getSqlMap().put("serial", serial);
        }
        return facilityMaintainSnapBiz.findJQJSONList(queryParam);
    }

    /**
     * 添加设备跳转页面
     *
     * @return
     */
    @RequestMapping("/addFacilityList")
    public ModelAndView addFacilityList(String maintainOrderId, String serial) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("maintainOrderId", maintainOrderId);
        modelAndView.addObject("serial", serial);
        modelAndView.setViewName("pages/admin/maintainOrder/addFacilityList");

        return modelAndView;
    }

    /**
     * 保存设备数据
     *
     * @param facilityIds
     * @param serial
     * @return
     */
    @RequestMapping("/showFacility")
    @ResponseBody
    public ResultDto showFacility(String facilityIds, String maintainOrderId, String serial, HttpServletRequest request
    ) {
        return facilityMaintainSnapBiz.saveFacility(facilityIds, maintainOrderId, serial, request);
    }

    /**
     * 添加工艺跳转页面
     *
     * @return
     */
    @RequestMapping("/addMaintainList")
    public ModelAndView addMaintainList(String facilityMaintainSnapIds, String maintainOrderId, String catId) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("facilityMaintainSnapIds", facilityMaintainSnapIds);
        modelAndView.addObject("maintainOrderId", maintainOrderId);
        modelAndView.addObject("catId", catId);
        modelAndView.setViewName("pages/admin/maintainOrder/addMaintainList");
        return modelAndView;
    }

    /**
     * 保存工艺数据
     *
     * @param facilityMaintainSnapIds
     * @param maintainId
     * @param maintainOrderId
     * @return
     */
    @RequestMapping("/showMaintain")
    @ResponseBody
    public ResultDto showMaintain(String facilityMaintainSnapIds, String maintainId, String maintainOrderId
    ) {
        return facilityMaintainSnapBiz.saveMaintain(facilityMaintainSnapIds, maintainId, maintainOrderId);
    }

    /**
     * 清除工艺
     *
     * @param facilityMaintainSnapIds
     * @return
     */
    @RequestMapping("/removeMaintain")
    @ResponseBody
    public ResultDto removeMaintain(String facilityMaintainSnapIds) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(facilityMaintainSnapIds);
        for (Object id : jsonArray) {
            FacilityMaintainSnap facilityMaintainSnap = facilityMaintainSnapBiz.findModel(StringConverters.null2Long(id));
            facilityMaintainSnap.setMaintainId(null);
            facilityMaintainSnap.setMaintainName(null);
            facilityMaintainSnapBiz.addOrUpdate(facilityMaintainSnap);
        }
        return ResultUtil.success();
    }

    /**
     * 删除维保数据
     *
     * @param facilityMaintainSnapIds
     * @return
     */
    @RequestMapping("/deleteFacilityMaintainSnap")
    @ResponseBody
    public ResultDto deleteFacilityMaintainSnap(String facilityMaintainSnapIds) {
        net.sf.json.JSONArray jsonArray = net.sf.json.JSONArray.fromObject(facilityMaintainSnapIds);
        for (Object id : jsonArray) {
            FacilityMaintainSnap facilityMaintainSnap = facilityMaintainSnapBiz.findModel(StringConverters.null2Long(id));
            facilityMaintainSnapBiz.deleteLogic(facilityMaintainSnap);
        }
        return ResultUtil.success();
    }

    /**
     * 指定接单人列表跳转页
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/assignUser")
    public ModelAndView assignUser(String orderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orderId", orderId);
        modelAndView.setViewName("pages/admin/maintainOrder/assignUser");
        return modelAndView;
    }

    /**
     * 指定岗位列表跳转页
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/assignPosition")
    public ModelAndView assignPosition(String orderId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("orderId", orderId);
        modelAndView.setViewName("pages/admin/maintainOrder/assignPosition");
        return modelAndView;
    }

    //指定人员json数据
    @RequestMapping("/getUserByArea")
    @ResponseBody
    public JSONObject getUserByArea(String orderId, HttpServletRequest request,
                                    @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                    @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(orderId));
        String authorityName = Configuration.getConfigurationByName("maintainAuthorityName");
        return systemUserBiz.getSystemUserJson(null, maintainOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam,maintainOrder.getEnterprise());
    }

    //指定岗位json数据
    @RequestMapping("/getPositionByArea")
    @ResponseBody
    public JSONObject getPositionByArea(String orderId, HttpServletRequest request,
                                        @RequestParam(value = "pageNo", required = false) String pageNowParam,
                                        @RequestParam(value = "pageSize", required = false) String pageSizeParam) {
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(orderId));
        String authorityName = Configuration.getConfigurationByName("maintainAuthorityName");
        return positionBiz.getPositionJson(null, maintainOrder.getEnterprise().getId() + "", authorityName, pageNowParam, pageSizeParam);
    }


    /**
     * 保存指定人
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    @RequestMapping("/saveAssignList")
    @ResponseBody
    public ResultDto saveAssignList(String assignIds, String orderId, HttpServletRequest request) {
        return maintainOrderBiz.assignUsers(assignIds, orderId, request);
    }

    /**
     * 保存指定岗位数据
     *
     * @param assignIds
     * @param orderId
     * @return
     */
    @RequestMapping("/saveAssignPosition")
    @ResponseBody
    public ResultDto saveAssignPosition(String assignIds, String orderId, HttpServletRequest request) {
        return maintainOrderBiz.assignPositions(assignIds, orderId, request);
    }

    /**
     * 设置截止日期
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/assignDatePage")
    public ModelAndView assignDatePage(String orderId) {

        ModelAndView modelAndView = new ModelAndView();
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(orderId));
        modelAndView.addObject("maintainOrder", maintainOrder);
        modelAndView.setViewName("pages/admin/maintainOrder/assignDate");
        return modelAndView;
    }

    /**
     * 设置截止日期
     *
     * @param id
     * @param endDate
     * @param request
     * @return
     */
    @RequestMapping("/saveAssignDate")
    @ResponseBody
    public ResultDto saveAssignDate(String id, String endDate, HttpServletRequest request) {
        return maintainOrderBiz.saveAssignDate(id, endDate, request);

    }

    /**
     * 审核列表页面
     *
     * @return
     */
    @RequestMapping("/auditList")
    public ModelAndView auditList() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/maintainOrder/audit");
        return modelAndView;
    }


    /**
     * 审核数据
     *
     * @param pageNowParam
     * @param pageSizeParam
     * @param searchName
     * @param searchType
     * @param searchAudit
     * @param request
     * @return
     */
    @RequestMapping("/auditListJson")
    @ResponseBody
    public JSONObject auditListJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                                    @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                    @RequestParam(value = "searchName", required = false) String searchName,
                                    @RequestParam(value = "searchType", required = false) String searchType,
                                    @RequestParam(value = "searchAudit", required = false) String searchAudit,
                                    @RequestParam(value = "start", required = false) String start,
                                    @RequestParam(value = "end", required = false) String end,
                                    HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = systemUserBiz.findModel(StringConverters.null2Long(SessionKeyUtils.getSessionUser(request).getId()));
        if (enterprise != null) {
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        }
        queryParam.getSqlMap().put("startTime", start);
        queryParam.getSqlMap().put("endTime", end);
        queryParam.getSqlMap().put("searchName", searchName);
        queryParam.getSqlMap().put("orderType", searchType);
        queryParam.getSqlMap().put("searchAudit", searchAudit);
        queryParam.getSqlMap().put("auditIn", "auditIn");

        if (systemUser.getOperationRole().equals("common")) {
            //岗位
            Set<Position> positions = systemUser.getPositionSet();
            Position position = systemUser.getPosition(enterprise, positions);

            //部门
            Set<SystemUserOrganization> systemUserOrganizations = systemUser.getSystemUserOrganizationSet();
            SystemUserOrganization systemUserOrganization = systemUser.getOrganization(enterprise, systemUserOrganizations);

            String userInformation = systemUser.getId() + "," + position.getId() + "," + systemUserOrganization.getOrganization().getId();
            queryParam.getSqlMap().put("auditAuthority", userInformation);
        }

        return maintainOrderBiz.findJSONList(queryParam);
    }

    /**
     * 审核不通过页面
     *
     * @param id
     * @param type
     * @return
     */
    @RequestMapping("/auditOrderEdit")
    public ModelAndView auditOrderEdit(String id, String type) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("ids", id);
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("maintainOrder", maintainOrder);
        modelAndView.setViewName("pages/admin/maintainOrder/unPassOrder");
        return modelAndView;
    }

    /**
     * 终极审核评分页面
     *
     * @param id
     * @return
     */
    @RequestMapping("/judgeOrder")
    public ModelAndView judgeOrder(String id) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("ids", id);
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(id));
        modelAndView.addObject("maintainOrder", maintainOrder);
        modelAndView.setViewName("pages/admin/maintainOrder/judgeOrder");
        return modelAndView;
    }

    /**
     * 审核工单
     *
     * @param ids
     * @param type
     * @param reason
     * @param request
     * @return
     */
    @RequestMapping("/auditOrder")
    @ResponseBody
    public ResultDto auditOrder(String ids, String type, String reason, String score, String remark, HttpServletRequest request) {
        return maintainOrderBiz.auditOrder(ids, type, reason, score, remark, request);
    }

    /**
     * 审核工单
     * 终审和9审核不通过接口
     */
    @RequestMapping("/editOrder")
    @ResponseBody
    public ResultDto editOrder(String ids, String type, String reason, String score, String remark, HttpServletRequest request) {
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(ids);
        return maintainOrderBiz.auditOrder(jsonArray.toString(), type, reason, score, remark, request);
    }

    /**
     * DashBoard评价统计
     */
    @RequestMapping("/countScore")
    @ResponseBody
    public JSONObject countScore(String enterpriseId, String systemUserId) {
        return maintainOrderBiz.countScore(enterpriseId, systemUserId);
    }

    /**
     * 设备导出
     */
    @RequestMapping(value = "/exportOrder", produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public void exportOrder(HttpServletResponse response, HttpServletRequest request) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (systemUser == null) {
            return;
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise == null) {
            return;
        }
        String searchCode = "";
        String searchName = "";
        String searchType = "";
        String searchDegree = "";
        String searchOrderStatus = "";
        String startTime = "";
        String endTime = "";
        try {
            searchCode = URLDecoder.decode(request.getParameter("searchCode"), "UTF-8");
            searchName = URLDecoder.decode(request.getParameter("searchName"), "UTF-8");
            searchType = URLDecoder.decode(request.getParameter("searchType"), "UTF-8");
            searchDegree = URLDecoder.decode(request.getParameter("searchDegree"), "UTF-8");
            searchOrderStatus = URLDecoder.decode(request.getParameter("searchOrderStatus"), "UTF-8");
            startTime = URLDecoder.decode(request.getParameter("startTime"), "UTF-8");
            endTime = URLDecoder.decode(request.getParameter("endTime"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId() + "");
        queryParam.getSqlMap().put("searchCode", searchCode);
        queryParam.getSqlMap().put("searchName", searchName);
        queryParam.getSqlMap().put("orderType", searchType);
        queryParam.getSqlMap().put("degree", searchDegree);
        queryParam.getSqlMap().put("searchOrderStatus", searchOrderStatus);
        queryParam.getSqlMap().put("searchDate1", startTime);
        queryParam.getSqlMap().put("searchDate2", endTime);
        List<MaintainOrder> maintainOrderList = maintainOrderBiz.findList(queryParam);

        JSONArray jsonArray = new JSONArray();
        if (CollectionUtils.isNotEmpty(maintainOrderList)) {
            for (MaintainOrder maintainOrder : maintainOrderList) {
                JSONObject json = maintainOrder.toExportJSONObject();
                //查询实施单（设备工艺数量）
                QueryParam queryParam1 = new QueryParam();
                queryParam1.getSqlMap().put("maintainOrderId",maintainOrder.getId()+"");
                long count = facilityMaintainSnapBiz.totalRecord(queryParam1.getSqlMap());
                json.put("snapCount",count);
                jsonArray.add(json);
            }
        }
        try {
            ExcelExport.exportExcelFile("维保工单", ExcelExportMap.MAINTAIN_ORDER_LIST_EXPORT_MAP(), jsonArray, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 导出工单详情
     */
    @RequestMapping("/exportDetailExcel")
    @ResponseBody
    public void exportDetailExcel(HttpServletRequest request, HttpServletResponse response, String orderId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        MaintainOrder maintainOrder = maintainOrderBiz.findModel(StringConverters.null2Long(orderId));
        try {
            String path = request.getServletContext().getRealPath("")
                    + "/doc/maintainOrder.xls";//这个是我的excel模板
            InputStream in = null;
            in = new FileInputStream(new File(path));
            HSSFWorkbook work = new HSSFWorkbook(in);
            // 得到excel的第0张表
            HSSFSheet sheet = work.getSheetAt(0);

            HSSFFont hssfFont=work.createFont();
            hssfFont.setFontHeightInPoints((short)12);//设置字体大小
            CellStyle cellStyle = work.createCellStyle();//基础样式样式带边框字体，用于表头
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);//下边框
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
            cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());// 设置背景色
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            ((HSSFCellStyle) cellStyle).setFont(hssfFont);

            CellStyle cellStyle1 = work.createCellStyle();//样式文本右对齐。用于日期
            cellStyle1.setAlignment(CellStyle.ALIGN_RIGHT);
            ((HSSFCellStyle) cellStyle1).setFont(hssfFont);

            CellStyle cellStyle2 = work.createCellStyle();//样式样式带边框字体和背景颜色，用于内容
            cellStyle2.setBorderBottom(HSSFCellStyle.BORDER_THIN);//下边框
            cellStyle2.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
            cellStyle2.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
            cellStyle2.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
            ((HSSFCellStyle) cellStyle2).setFont(hssfFont);

            HSSFRow row = sheet.getRow(0);
            HSSFCell cell = row.getCell(0);
            cell.setCellValue("维护保养工单(" + maintainOrder.getOrderName() + "_" + DateTimeUtils.formatDateToStringWithTime(maintainOrder.getCreateDate()) + ")");

            row = sheet.getRow(1);//报告时间，第二行第一列
            cell = row.getCell(0);
            cell.setCellValue("报告日期：" + DateTimeUtils.formatDateToStringWithTime(new Date()));
            cell.setCellStyle(cellStyle1);

            row = sheet.getRow(2);//工单类型，第三行第三列
            cell = row.getCell(2);
            cell.setCellValue("维护保养");

            row = sheet.getRow(2);//所属部门，第三行第7列
            cell = row.getCell(6);
            cell.setCellValue(maintainOrder.getOrganization() != null ? maintainOrder.getOrganization().getOrganizationName() : "");

            row = sheet.getRow(2);//完成时间，第三行第10列
            cell = row.getCell(9);
            cell.setCellValue(DateTimeUtils.formatDateToStringWithTime(maintainOrder.getFinishTime()));

            //设备工艺信息
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("maintainOrderId", orderId);
            int count = 4;
            List<FacilityMaintainSnap> facilityMaintainSnaps = facilityMaintainSnapBiz.findList(queryParam);
            for (FacilityMaintainSnap f : facilityMaintainSnaps) {
                sheet.addMergedRegion(new CellRangeAddress(count, count, 0, 11));
                row = sheet.createRow(count);//报告时间

                row.createCell(0).setCellValue("报告日期：" + DateTimeUtils.formatDateToStringWithTime(new Date()));
                row.getCell(0).setCellStyle(cellStyle1);
                count++;
                sheet.addMergedRegion(new CellRangeAddress(count, count, 0, 1));//合并单元格
                sheet.addMergedRegion(new CellRangeAddress(count, count, 2, 4));
                sheet.addMergedRegion(new CellRangeAddress(count, count, 6, 10));
                row = sheet.createRow(count);//模块名称
                row.createCell(0).setCellValue("维保名称");

                row.getCell(0).setCellStyle(cellStyle);
                row.createCell(1).setCellStyle(cellStyle);

                row.createCell(2).setCellValue(maintainOrder.getOrderName());
                row.getCell(2).setCellStyle(cellStyle2);
                row.createCell(3).setCellStyle(cellStyle2);
                row.createCell(4).setCellStyle(cellStyle2);

                row.createCell(5).setCellValue("资产编号");
                row.getCell(5).setCellStyle(cellStyle);
                cell.setCellStyle(cellStyle);

                row.createCell(6).setCellValue(f.getFacilityName()+"("+f.getFacilityCode()+")");
                row.getCell(6).setCellStyle(cellStyle2);
                row.createCell(7).setCellStyle(cellStyle2);
                row.createCell(8).setCellStyle(cellStyle2);
                row.createCell(9).setCellStyle(cellStyle2);
                row.createCell(10).setCellStyle(cellStyle2);
                row.createCell(11).setCellStyle(cellStyle2);

                count++;
                sheet.addMergedRegion(new CellRangeAddress(count, count, 0, 1));
                sheet.addMergedRegion(new CellRangeAddress(count, count, 2, 4));
                sheet.addMergedRegion(new CellRangeAddress(count, count, 6, 9));
                row = sheet.createRow(count);//模块名称
                row.createCell(0).setCellValue("区域");
                row.getCell(0).setCellStyle(cellStyle);
                row.createCell(1).setCellStyle(cellStyle);

                Facility facility = facilityBiz.findModel(f.getFacilityId());
                row.createCell(2).setCellValue(facility.getArea() != null ? facility.getArea().getAreaName() : "");
                row.getCell(2).setCellStyle(cellStyle2);
                row.createCell(3).setCellStyle(cellStyle2);
                row.createCell(4).setCellStyle(cellStyle2);

                row.createCell(5).setCellValue("详细位置");
                row.getCell(5).setCellStyle(cellStyle);

                row.createCell(6).setCellValue(facility.getDetailPosition()!=null?facility.getDetailPosition():"");
                row.getCell(6).setCellStyle(cellStyle2);
                row.createCell(7).setCellStyle(cellStyle2);
                row.createCell(8).setCellStyle(cellStyle2);
                row.createCell(9).setCellStyle(cellStyle2);

                row.createCell(10).setCellValue("执行结果");
                row.getCell(10).setCellStyle(cellStyle);
                row.createCell(11).setCellValue("正常");
                row.getCell(11).setCellStyle(cellStyle2);

                count++;
                row = sheet.createRow(count);
                row.createCell(0).setCellValue("检查点名");
                row.getCell(0).setCellStyle(cellStyle);
                row.createCell(1).setCellValue("运行场景");
                row.getCell(1).setCellStyle(cellStyle);
                row.createCell(2).setCellValue("检查标准");
                row.getCell(2).setCellStyle(cellStyle);

                row.createCell(3).setCellValue("正常低值");
                row.getCell(3).setCellStyle(cellStyle);

                row.createCell(4).setCellValue("正常高值");
                row.getCell(4).setCellStyle(cellStyle);

                row.createCell(5).setCellValue("检查人");
                row.getCell(5).setCellStyle(cellStyle);

                row.createCell(6).setCellValue("完成时间");
                row.getCell(6).setCellStyle(cellStyle);

                row.createCell(7).setCellValue("检查结果");
                row.getCell(7).setCellStyle(cellStyle);

                row.createCell(8).setCellValue("是否正常");
                row.getCell(8).setCellStyle(cellStyle);

                row.createCell(9).setCellValue("发现问题");
                row.getCell(9).setCellStyle(cellStyle);

                row.createCell(10).setCellValue("解决措施");
                row.getCell(10).setCellStyle(cellStyle);

                row.createCell(11).setCellValue("备注");
                row.getCell(11).setCellStyle(cellStyle);
                count++;
                QueryParam queryParam1=new QueryParam();
                queryParam1.getSqlMap().put("resultNotnull",f.getId().toString());
                queryParam1.getSqlMap().put("facilityMaintainSnapId",f.getId().toString());
                queryParam1.setSqlOrder("order by application_scenarios_name");
                List<MaintainOrderWorkContent> maintainOrderWorkContents=maintainOrderWorkContentBiz.findList(queryParam1);
                for (MaintainOrderWorkContent m : maintainOrderWorkContents) {
                    //具体的维保内容
                    row = sheet.createRow(count);
                    row.createCell(0).setCellValue(m.getName());
                    row.getCell(0).setCellStyle(cellStyle2);

                    row.createCell(1).setCellValue(m.getApplication_scenarios_name());
                    row.getCell(1).setCellStyle(cellStyle2);
                    row.createCell(2).setCellValue(m.getInputTypeEnum().getName());
                    row.getCell(2).setCellStyle(cellStyle2);
                    row.createCell(3).setCellValue(m.getMinNumber()!=null?m.getMinNumber()+"":"");
                    row.getCell(3).setCellStyle(cellStyle2);

                    row.createCell(4).setCellValue(m.getMaxNumber()!=null?m.getMaxNumber()+"":"");
                    row.getCell(4).setCellStyle(cellStyle2);

                    row.createCell(5).setCellValue(m.getSystemUser() != null ? m.getSystemUser().getUserName() : "");
                    row.getCell(5).setCellStyle(cellStyle2);

                    row.createCell(6).setCellValue(DateTimeUtils.formatDateToStringWithTime(m.getFinishTime()));
                    row.getCell(6).setCellStyle(cellStyle2);

                    String result="";//检查结果
                    if(m.getResult()!=null&&m.getResult().equals("false")){
                        result="异常";
                    }else if(m.getResult()!=null&&m.getResult().equals("true")){
                        result="正常";
                    }else{
                        result=m.getResult();
                    }
                    row.createCell(7).setCellValue(result);
                    row.getCell(7).setCellStyle(cellStyle2);

                    row.createCell(8).setCellValue(m.getAbnormal()!=null&&m.getAbnormal()?"异常":"正常");
                    row.getCell(8).setCellStyle(cellStyle2);



                    QueryParam queryParam2 = new QueryParam();
                    queryParam2.getSqlMap().put("contentId", m.getId() + "");
                    List<WorkContentRemark> workContentRemarks = workContentRemarkBiz.findList(queryParam2);//备注
                    if (CollectionUtils.isNotEmpty(workContentRemarks)) {
                        row.createCell(9).setCellValue(workContentRemarks.get(0).getQuestion());

                        row.createCell(10).setCellValue(workContentRemarks.get(0).getMeasure());

                        row.createCell(11).setCellValue(workContentRemarks.get(0).getRemark());
                        row.getCell(9).setCellStyle(cellStyle2);
                        row.getCell(10).setCellStyle(cellStyle2);
                        row.getCell(11).setCellStyle(cellStyle2);

                    }else{
                        row.createCell(9).setCellStyle(cellStyle2);
                        row.createCell(10).setCellStyle(cellStyle2);
                        row.createCell(11).setCellStyle(cellStyle2);
                    }
                    count++;
                }
                count = count + 3;
            }

            String address = DateTimeUtils.format(new Date(), "yyyy-MM-dd");
            String fileName = "维保工单详情";// URLEncoder.encode("年度计划", "UTF-8");
            fileName = new String(fileName.getBytes("gbk"), "iso8859-1");
            OutputStream os = response.getOutputStream();// 取得输出流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName + "_" + address + ".xls");
            work.write(os);
            os.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件路径错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("文件输入流错误");
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }


    }

    public static void main(String[] args) {
        Jedis jedis=new Jedis();
        for(int i=0;i<1000;i++){
            jedis.pfadd("codehole","user"+i);
           long total= jedis.pfcount("codehole");
           if(total!=i+1){
               System.out.println("false");
               break;
           }
        }
        jedis.close();
    }
}
